<?php 
namespace App\Http\Controllers\TongGaoApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Mysql\tonggao\article;
use App\Models\Mysql\tonggao\term;
use App\Models\Mysql\tonggao\term_detail;
use App\Models\Mysql\tonggao\sentence;
use Symfony\Component\DomCrawler\Crawler;
use App\libraries\diff\Diff;	

class ExtractTermTranController extends Controller
{
//	use GlobalData;

	const ROUTE_PREFIX = '/api/*';

	protected $request;

	protected $curTime;

	protected $debug;


	/**
	 * 创建新的`ExtractTermTranController`控制器实例
	 * @param \Illuminate\Http\Request $request
	 */
	public function __construct(Request $request)
	{
		$this->request = $request;
		$this->error = [];
		$this->curTime = time();

		if(config('app.debug')) {
			$this->debug = true;
			error_reporting(E_ALL | E_STRICT);
		} else {
			$this->debug = false;
		}
	}
	
	public function getTermDetail(){
		$term_id = intval($this->request->term_id);
		$criteria = addslashes($this->request->criteria);
		
		$sentenceSql = $this::criteria2Sentencesql($criteria);
		$sentences = term_detail::select("select term_detail.id,sentence.content,sentence.translation,term_detail.english,term_detail.english_pos from term_detail,sentence where term_detail.sentence_id=sentence.id and $sentenceSql and term_id=$term_id and has_big_term=0 group by sentence_id order by seq_no,occur_no");
		return responseJson('ok', $sentences, TRUE);
	}
	
	public function criteria2Sentencesql($criteria){
		$ret = "1";
		switch($criteria){
			case "lamrim":
				$article = article::select("select id from article where name=\"gl\"");
				if (empty($article))
					$ret = "0";
				else
					$ret = "term_detail.article_id={$article[0]->id}";
				break;
		}
		return $ret;
	}

//test stub for matchTermTran
//http://localhost/tonggao/public/api/tonggao/extract/t_match_term_tran/1/lamrim/enlightenment;the%20development%20of%20spirit/0	
	public function tMatchTermTran(){
		$term_id = intval($this->request->term_id);
		$criteria = addslashes($this->request->criteria);
		$english_keys = addslashes($this->request->english_keys);
		$mode = intval($this->request->mode);
		$english_key_array = explode(";",$english_keys);
		$this::matchTermTran($term_id,$criteria,$english_key_array,$mode);
	}
	
	public function matchTermTran($term_id,$criteria,$english_key_array,$mode){
		$debug1 = true;
		$debug2 = true;
		$dryRun = false;
		foreach($english_key_array as $k=>$v){
			$english_key_matched_count [] = 0;
		}

		$sentenceSql = $this::criteria2Sentencesql($criteria);
		$term_details = term_detail::select("select term_detail.id term_detail_id, term_detail.sentence_id,term_detail.occur_no,sentence.translation,term_detail.english,term_detail.english_pos , term_detail.state from term_detail,sentence where term_detail.sentence_id=sentence.id and $sentenceSql and term_id=$term_id and has_big_term=0 order by seq_no,occur_no");

		$result = array();$result_i=0;
		$last_sentence_id=$last_occur_no=$last_found_start_word_pos=-1;
		
		foreach($term_details as $term_detail){
			$result[$result_i]['matched']= 0;
			$result[$result_i]['matched_key_i']= -1;
			$result[$result_i]['candidates']= $result[$result_i]['matched_english_pos']='';
			
			$cur_sentence_id = $term_detail->sentence_id;
			$cur_occur_no = $term_detail->occur_no;
			$cur_translation = $term_detail->translation;
			$out_of_up_range_pos = mb_strlen($cur_translation)+1;
			$cur_mode = $term_detail->state;
			
			if ($debug1){
				echo "------------------------------------------------------</br>";
				echo "cur_sentence_id=$cur_sentence_id cur_occur_no=$cur_occur_no  last_found_start_word_pos=$last_found_start_word_pos</br>";
				echo "$cur_translation</br>";
			}
			
			//0：skip state in (01,02,12), 1: skip state==(02,12), 2: skip state=12, 99(>=3): done with everything
			switch($mode){
				case 0:
					$skipArray = array(1,2,12);
					break;
				case 1:
					$skipArray = array(2,12);
					break;
				case 2:
					$skipArray = array(12);
					break;
				case 99:
					$skipArray = array();
					break;
			}
			if (in_array($cur_mode,$skipArray)){
				$last_sentence_id = $cur_sentence_id;
				$last_occur_no = $cur_occur_no;
				
				$cur_english_pos = $term_detail->english_pos;
				$last_found_word_pos = english_pos_to_word_pos($cur_english_pos,$cur_translation);
				$last_found_start_word_pos = $last_found_word_pos[0];
				continue;
			}
			
			if($cur_sentence_id<>$last_sentence_id){
				$cur_start_pos=0;
			}else{
				if($cur_occur_no==$last_occur_no+1){
					$cur_start_pos=$last_found_start_word_pos+1;
					//if out of range, set last_xxxx and then continue;
				}else{
					echo "$last_sentence_id $last_occur_no $cur_sentence_id $cur_occur_no error</br>";
				}
			}
			
			$matched = false; $matched_key=$matched_english_pos="";$matched_key_i=-1;
			$candidate_list = array(); 
			$min_found_pos = $out_of_up_range_pos;
			foreach($english_key_array as $english_key_i=>$v){
				$r = pos_in_sentence($v,$cur_translation,$cur_start_pos);
				if (!empty($r)){
					$start_len_arr = array();
					foreach($r as $vv){
						$start_len_arr []= $vv['start'].",".$vv['len'];
					}
					$start_len = implode(";",$start_len_arr);
					$candidate_list []= $v."[e]".$start_len;
					
					$cur_found_pos = $r[0]['start'];
					if (($cur_found_pos<$min_found_pos) || ($cur_found_pos==$min_found_pos && mb_strlen($v)>mb_strlen($matched_key))){
						echo "cur_found_pos=$cur_found_pos min_found_pos=$min_found_pos</br>";
						$matched = true;
						$matched_key = $v;
						$matched_key_i = $english_key_i;
						$min_found_pos=$cur_found_pos;
						$matched_english_pos = $start_len;
						$last_r = $r[count($r)-1];
						$last_found_start_word_pos = $last_r['startWordPos']  ;
						//var_dump($r);var_dump($start_len_arr);echo "$start_len</br>";var_dump($last_start_len);
						if ($debug1)	echo "cur_occur_no=$cur_occur_no  last_found_start_word_pos=$last_found_start_word_pos</br>";
					}
				}
			}
			
			$last_sentence_id=$cur_sentence_id;
			$last_occur_no=$cur_occur_no;
			if ($matched){
				$result[$result_i]['matched']= 1;
				$result[$result_i]['matched_key_i'] = $matched_key_i; //index of english_list3
				$result[$result_i]['matched_english_pos'] = $matched_english_pos;
				$result[$result_i]['candidates'] = implode("|",$candidate_list);
				//for debug purpose
				$result[$result_i]['sentence_id']=$cur_sentence_id;
				$result[$result_i]['occur_no']=$cur_occur_no;
				
				$english_key_matched_count[$matched_key_i]++;
				
				$pass_pos_in_sentence = 1;
				if (!$dryRun){
					$sql = "update term_detail SET `english`=\"$english_key_array[$matched_key_i]\", `english_pos`=\"$matched_english_pos\", pass_pos_in_sentence=$pass_pos_in_sentence, state=1 where id={$term_detail->term_detail_id}";
					echo "$sql</br>";
					term_detail::select($sql);
				}

			}else{
				$last_found_start_word_pos = $out_of_up_range_pos;
			}
			$result_i++;
			
			if ($debug2){
				$v=$result[$result_i-1];
				if ($v['matched']==1){
					$r=$v['matched_english_pos'];
					$start_len_arr=explode(";",$r);
					var_dump($start_len_arr);
					foreach($start_len_arr as $start_len){
						$temp_start_len=explode(",",$start_len);
						echo "<font color=\"red\">".mb_substr($cur_translation,$temp_start_len[0],$temp_start_len[1])." "."</font>";
					}
					echo "</br>------------------</br>";
				}
			}
			if ($debug1)
				var_dump($result[$result_i-1]);
		}
		
	}

//http://localhost/tonggao/public/api/tonggao/extract/match_term_tran/1/lamrim/0;1;2;3/enlightenment;the%20development%20of%20spirit
//workable, it can be tested directly by the above url, will be changed to be database based.
	public function matchTermTran_v1(){
		$term_id = intval($this->request->term_id);
		$criteria = addslashes($this->request->criteria);
		
		$indexes = addslashes($this->request->indexes);
		//$term_detail_ids = addslashes($this->request->term_detail_ids);
		$english_keys = addslashes($this->request->english_keys);
		
		$index_list = explode(";",$indexes);
		//$term_detail_list = explode(";",$term_detail_ids);
		$english_key_list = explode(";",$english_keys);
		
		
		if (!empty($english_key_list)){
			$english_key_list2=array();
			foreach($english_key_list as $english_key){
				$english_key_list2 [$english_key] = mb_strlen($english_key);
			}
			//var_dump($english_key_list2);
			arsort($english_key_list2);
			
			$english_key_list3 = array();
			$english_key_matched_count = array();
			foreach($english_key_list2 as $k=>$v){
				$english_key_list3 [] = $k;
				$english_key_matched_count [] = 0;
			}
		}
		//var_dump($english_key_list);
		//$temp_r=term::select("select chinese_key,sentence.content,sentence.translation from term, term_detail,sentence where term.id=term_detail.term_id and sentence.id=term_detail.sentence_id and term_detail.id in ($term_detail_ids) order by seq_no, occur_no");
		$sentenceSql = $this::criteria2Sentencesql($criteria);
		$sentences = term_detail::select("select term_detail.id,term_detail.sentence_id,term_detail.occur_no,sentence.content,sentence.translation,term_detail.english,term_detail.english_pos from term_detail,sentence where term_detail.sentence_id=sentence.id and $sentenceSql and term_id=$term_id and has_big_term=0 group by sentence_id order by seq_no,occur_no");

		
		$result = array();
		$last_sentence_id=$last_occur_no=$last_found_pos=-1;
		foreach($index_list as $index_i=>$index){
			$result[$index_i]['matched']= 0;
			$result[$index_i]['matched_key_i']= -1;
			$result[$index_i]['candidates']= $result[$index_i]['matched_english_pos']='';
			
			$cur_sentence_id = $sentences[$index]->sentence_id;
			$cur_occur_no = $sentences[$index]->occur_no;
			$cur_translation = $sentences[$index]->translation;
			$out_of_up_range_pos = strlen($cur_translation)+1;
			
			if($cur_sentence_id<>$last_sentence_id){
				$cur_start_pos=0;
			}else{
				if($cur_occur_no==$last_occur_no+1){
					$cur_start_pos=$last_found_pos+1;
					//if out of range, set last_xxxx and then continue;
				}else{
					$cur_start_pos=($sentences[$index-1]->occur_no)+1;
				}
			}
			//echo "$cur_translation</br>";
			
			$matched = false; $matched_key=$matched_english_pos="";$matched_key_i=-1;
			$candidate_list = array(); 
			$min_found_pos = $out_of_up_range_pos;
			foreach($english_key_list3 as $english_key_i=>$v){
				$r = pos_in_sentence($v,$cur_translation,$cur_start_pos);
				if (!empty($r)){
					$candidate_list []= $v;
					$cur_found_pos = $r[0]['start'];
					if ($cur_found_pos<$min_found_pos){
						$matched = true;
						$matched_key = $v;
						$matched_key_i = $english_key_i;
						$min_found_pos=$cur_found_pos;
						$start_len_arr = array();
						foreach($r as $vv){
							$start_len_arr []= $vv['start'].",".$vv['len'];
						}
						$matched_english_pos = implode(";",$start_len_arr);
					}
				}
			}
			
			$last_sentence_id=$cur_sentence_id;
			$last_occur_no=$cur_occur_no;
			if ($matched){
				$result[$index_i]['matched']= 1;
				$result[$index_i]['matched_key_i'] = $matched_key_i;
				$result[$index_i]['matched_english_pos'] = $matched_english_pos;
				$result[$index_i]['candidates'] = implode(";",$candidate_list);
				$english_key_matched_count[$matched_key_i]++;
				$last_found_pos = $min_found_pos;
				//need to add candidates
			}else{
				$last_found_pos = $out_of_up_range_pos;
			}
		}
		//var_dump($result);
		return responseJson('ok', $result, TRUE);
	}
	
	public function showTermSentence(){
		//$chinese_key = "菩提";	$english_key_list = array("enlightenment");
		//$chinese_key = "发心";	$english_key_list = array("the spirit of enlightenment","the development of enlightenment","enlightenment");
		//$chinese_key = "在家";	$english_key_list = array("householder","lay","household","layperson");
		$chinese_key = "戒律";	$english_key_list = array("ethical discipline");
		
		if (!empty($english_key_list)){
			$english_key_list2=array();
			foreach($english_key_list as $english_key){
				$english_key_list2 [$english_key] = mb_strlen($english_key);
			}
			var_dump($english_key_list2);
			arsort($english_key_list2);
			
			$english_key_list = array();
			foreach($english_key_list2 as $k=>$v){
				$english_key_list [$k] = 0;
			}
		}
		var_dump($english_key_list);
		$temp_r=term::select("select chinese_key,sentence.content,sentence.translation from term, term_detail,sentence where term.id=term_detail.term_id and term_detail.sentence_id=sentence.id and has_big_term=0 and term_detail.article_id=56 and chinese_key=\"$chinese_key\"");
		//$temp_r=term::select("select chinese_key,sentence.content,sentence.translation from term, term_detail,sentence where term.id=term_detail.term_id and term_detail.sentence_id=sentence.id and has_big_term=0 and term_detail.article_id=56 and chinese_key=\"$chinese_key\" and sentence.translation not like \"%clear%\" and sentence.translation not like \"%pure%\" and sentence.translation not like \"%purify%\" and sentence.translation not like \"%purified%\"");
		
		foreach($temp_r as $temp_r_v){
			$part = "NOT FOUND";
			foreach($english_key_list as $k=>$v){
				//echo "k=$k v=$v</br>";
				
				//if (mb_strpos($temp_r_v->translation,$k)!==false){
				if (!empty(pos_in_sentence($k,$temp_r_v->translation))){	
					$english_key_list[$k]++;
					$part=$k;
				}
			}
			echo "{$temp_r_v->content}</br>{$temp_r_v->translation}|$part</br></br>";
		}
		echo count($temp_r);
		var_dump($english_key_list);
	}

	public function searchHighFreqWords(){
		$puncturesEN = array(",","\.","\?","!",":",'\"',"\'","-",";","\(","\)","\[","\]");
		$puncturesCN = array("，","。","？","！","：",'“','”',"‘","’","-","；","《","》","、","（","）","…","·","—","　");
		$puncturesPattern="/[0-9]|".implode("|",array_merge($puncturesEN,$puncturesCN))."/";	
		
		$chinese_key = "清净";
		
		$temp_r=term::select("select chinese_key,sentence.content,sentence.translation from term, term_detail,sentence where term.id=term_detail.term_id and term_detail.sentence_id=sentence.id and has_big_term=0 and term_detail.article_id=56 and chinese_key=\"$chinese_key\"");
		$allWords=array();
		foreach($temp_r as $temp_r_v){
			$sentence = $temp_r_v->translation;
			$sentence = preg_replace($puncturesPattern," ",$sentence);	
			//echo "$sentence</br>";
			$allWords = array_merge($allWords,explode(" ",$sentence));
		}
		//print_r(array_count_values($allWords));
		$b=array_count_values($allWords);
		arsort($b);
		print_r($b);
		
	}
	
	
} //!- NLPController
?>
